package com.project.class4_6;

public class Test {
    public static void main(String[] args) {
        AccessObj obj = new AccessObj();
        new OneThread(obj);
        new TwoThread(obj);
    }
}

class AccessObj{
    public boolean isRun = true;
}

class OneThread extends Thread{
    private AccessObj obj;
    public OneThread(AccessObj obj){
        this.obj = obj;
        this.start();
    }

    public void run(){
        while(true){
            synchronized (obj) {
                if(obj.isRun == true) {
                    System.out.print("A");
                    obj.isRun = false;
                    //通知等待访问obj对象的其他线程，可以继续访问obj
                    obj.notify();

                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else{
                    try {
                        //当前线程针对obj对象，进行等待
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class TwoThread extends Thread{
    private AccessObj obj;
    public TwoThread(AccessObj obj){
        this.obj = obj;
        this.start();
    }

    public void run(){
        while(true){
            synchronized (obj) {
                if(obj.isRun == false) {
                    System.out.print("B");
                    obj.isRun = true;
                    obj.notify();

                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else{
                    try {
                        obj.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}